from ..ScriptWidget import ScriptWidget
from enums.WidgetType import WidgetType
from PySide6.QtWidgets import QLabel, QComboBox, QPushButton
from ..ScriptInput import ScriptInput
from ..ScriptButton import ScriptButton
from windows.SubScriptEditWindow import SubScriptEditWindow
from enums.ConditionType import ConditionType
from enums.ZhConditionType import ZhConditionType
from enums.VarCompareType import VarCompareType
from enums.ZhVarCompareType import ZhVarCompareType
from ..condition.Condition import Condition


class If(ScriptWidget):
    def __init__(self, initType=None):
        # 如果条件成立，则执行脚本
        super(If, self).__init__(WidgetType.IF)
        self.initType = initType

        self.subScriptEditWindow = None

        self.labTitle = QLabel('如果:', self)
        self.labTitle.setFixedSize(30, self.lineHeight)
        self.addWidget(self.labTitle)

        self.newLineSpaceWidth = self.labTitle.width() + self.intervalX

        self.comConditionType = QComboBox(self)
        self.comConditionType.addItems(ZhConditionType.values())
        self.comConditionType.setCurrentIndex(0)
        self.comConditionType.currentTextChanged.connect(self.conditionTypeTextChanged)
        self.addWidget(self.comConditionType)

        # 编辑脚本
        self.btnEdit = ScriptButton(self, '编辑', onClick=self.edit)
        self.addWidget(self.btnEdit)

        if initType in ['edit', 'create']:
            self.addOperate()

        self.newLine()

        self.widgetCondition = Condition(self)
        self.lineHeight = self.widgetCondition.height()
        self.addWidget(self.widgetCondition)

    def edit(self):
        if self.subScriptEditWindow is None:
            self.subScriptEditWindow = SubScriptEditWindow(self)

        self.subScriptEditWindow.show()

    def conditionTypeTextChanged(self, conditionType):
        self.widgetCondition.zhConditionType = ZhConditionType(conditionType)

    @property
    def data(self):
        result = self.widgetCondition.data
        result["type"] = self.type.value
        result["sub_script"] = self.subScriptEditWindow.data
        result['enable'] = self.switchEnable.isChecked()
        return result

    @data.setter
    def data(self, data):
        self.setData(data)
        conditionType = ZhConditionType[data['condition_type'].upper()].value
        self.comConditionType.setCurrentText(conditionType)
        self.widgetCondition.zhConditionType = ZhConditionType(conditionType)
        self.widgetCondition.data = data
        self.subScriptEditWindow = SubScriptEditWindow(self, data['sub_script'])
